package com.shigu.wx.web.services;

import com.opentae.data.mall.beans.MoWxuserinfo;
import com.opentae.data.mall.examples.MoWxuserinfoExample;
import com.opentae.data.mall.interfaces.MoWxuserinfoMapper;
import com.shigu.main4.common.util.BeanMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.sword.wechat4j.api.WechatClient;
import org.sword.wechat4j.api.request.user.Cgi_binUserInfoGet;
import org.sword.wechat4j.api.response.user.UserInfo;

import java.io.IOException;
import java.util.List;

/**
 * 微信openId的处理服务
 */
@Service
public class WxOpenidService {

    private static final Logger logger = LoggerFactory.getLogger(WxOpenidService.class);

    @Autowired
    private MoWxuserinfoMapper moWxuserinfoMapper;

    @Autowired
    private WxTokenService wxTokenService;


    /**
     * 登陆时
     * @param openid
     */
    public void login(String openid,Long userId) throws IOException {
        if (StringUtils.isEmpty(openid)) {
            return;
        }
        MoWxuserinfoExample example=new MoWxuserinfoExample();
        example.createCriteria().andOpenIdEqualTo(openid);
        example.or().andUserIdEqualTo(userId);
        List<MoWxuserinfo> infos=moWxuserinfoMapper.selectByExample(example);
        if (infos.size()==1) {//就一个
            MoWxuserinfo info=infos.get(0);
            info.setLoged(true);
            info.setOpenId(openid);
            info.setUserId(userId);
            moWxuserinfoMapper.updateByPrimaryKeySelective(info);
            fullWxinfo(info);
            return;
        }else if(infos.size()==0){//需要给它建一个
            createWxinfo(openid,userId);
        }

        //假如多个，要分是openid相同还是userId相同
        Boolean hasAllSame=false;//是否有都相同
        for(int i=0;i<infos.size();i++){
            MoWxuserinfo info=infos.get(i);
            if (info.getOpenId().equals(openid)&&info.getUserId().equals(userId)) {//都相同
                info.setLoged(true);
                moWxuserinfoMapper.updateByPrimaryKeySelective(info);
                fullWxinfo(info);
                hasAllSame=true;
            }else{
                if (hasAllSame) {//如果都相同的都有了，有不同的就不需要了,只放最后一个
                    moWxuserinfoMapper.deleteByPrimaryKey(info.getInfoId());
                }else if(i<infos.size()-1){
                    moWxuserinfoMapper.deleteByPrimaryKey(info.getInfoId());
                }else{
                    info.setLoged(true);
                    info.setOpenId(openid);
                    info.setUserId(userId);
                    moWxuserinfoMapper.updateByPrimaryKeySelective(info);
                    fullWxinfo(info);
                    hasAllSame=true;
                }
            }
        }
        //如果全部没有取到过微信的
    }

    /**
     * 登出时
     */
    public void logout(String openid){
        if (StringUtils.isEmpty(openid)) {
            return;
        }
        MoWxuserinfoExample example=new MoWxuserinfoExample();
        example.createCriteria().andOpenIdEqualTo(openid).andLogedEqualTo(true);
        MoWxuserinfo info=new MoWxuserinfo();
        info.setLoged(false);
        moWxuserinfoMapper.updateByExampleSelective(info,example);
    }
    /**
     * 按openid查userId，可登陆的userID
     * @param openid
     * @return
     */
    public Long selLogedUserIdByOpenid(String openid){
        MoWxuserinfoExample example=new MoWxuserinfoExample();
        example.createCriteria().andOpenIdEqualTo(openid).andLogedEqualTo(true);
        List<MoWxuserinfo> infos=moWxuserinfoMapper.selectByExample(example);
        if (infos.size()==0) {
            return null;
        }
        return infos.get(0).getUserId();
    }

    /**
     * 获取一个用户的微信详细信息
     * @param openid
     * @param userId
     * @return 返回关注状态，1代表已关注
     * @throws IOException
     */
    public Integer createWxinfo(String openid,Long userId) throws IOException {
        WechatClient client = new WechatClient();
        //下面开始测试
        Cgi_binUserInfoGet userInfoGet=new Cgi_binUserInfoGet();
        userInfoGet.setOpenid(openid);
        userInfoGet.setLang("zh_CN");
        UserInfo info=client.execute(userInfoGet,wxTokenService.getSystemToken().getAccess_token());
        //建立数据库记录
        MoWxuserinfoExample example=new MoWxuserinfoExample();
        example.createCriteria().andOpenIdEqualTo(openid);
        example.or().andUserIdEqualTo(userId);
        moWxuserinfoMapper.deleteByExample(example);
        MoWxuserinfo in= BeanMapper.map(info,MoWxuserinfo.class);
        if (StringUtils.isNotEmpty(in.getNickname())) {
            in.setNickname(removeFourChar(in.getNickname()));
        }
        in.setUserId(userId);
        in.setOpenId(openid);
        moWxuserinfoMapper.insertSelective(in);
        return info.getSubscribe();
    }

    public static String removeFourChar(String content) {
        byte[] conbyte = content.getBytes();
        for (int i = 0; i < conbyte.length; i++) {
            if ((conbyte[i] & 0xF8) == 0xF0) {
                for (int j = 0; j < 4; j++) {
                    conbyte[i + j] = 0x30;// 0x30 int=48   字符=0
                }
                i += 3;
            }
        }
        content = new String(conbyte);
        return content.replaceAll("0000", "");
    }

    /**
     * 补全微信信息，如果微信信息不全，以此来补全微信信息
     * @param info
     */
    public void fullWxinfo(MoWxuserinfo info){
        try {
            if (StringUtils.isEmpty(info.getNickname())) {
                WechatClient client = new WechatClient();
                Cgi_binUserInfoGet userInfoGet=new Cgi_binUserInfoGet();
                userInfoGet.setOpenid(info.getOpenId());
                userInfoGet.setLang("zh_CN");
                UserInfo wxinfo=client.execute(userInfoGet,wxTokenService.getSystemToken().getAccess_token());
                MoWxuserinfo updateinfo=BeanMapper.map(wxinfo,MoWxuserinfo.class);
                updateinfo.setInfoId(info.getInfoId());
                if (StringUtils.isNotEmpty(updateinfo.getNickname())) {
                    updateinfo.setNickname(removeFourChar(updateinfo.getNickname()));
                }
                moWxuserinfoMapper.updateByPrimaryKeySelective(updateinfo);
            }
        } catch (Exception e) {
            logger.error("微信信息补全失败",e);
        }
    }
}
